<template>
  <div class="min-h-200">
    <MyTable
      ref="$table"
      :columns="columns"
      :get-data="() => projectApi.operateList(detail.id)"
      :index="true"
      :auto-load="false"
      :is-pagination="false"
      :scroll-x="2200"
      list-key="/OMManagement:get"
    >
      <template #action>
        <n-button v-permission="`/OMManagement:add`" type="primary" @click="handleAdd">
          添加
        </n-button>
      </template>
    </MyTable>
    <MyDrawer ref="$form" :model-form="model" :disabled="type === 'view'" @submit="handleSubmit">
      <n-form-item
        label="服务器IP"
        path="ip"
        :rule="[{ required: true, message: '服务器IP不能为空!' }]"
      >
        <n-input v-model:value="model.ip" clearable :maxlength="50" />
      </n-form-item>
      <n-form-item label="区域" path="area">
        <AsyncSelect v-model:value="model.area" options="OM_AREA" />
      </n-form-item>
      <n-form-item label="类型" path="serverOwner">
        <AsyncSelect v-model:value="model.serverOwner" options="SERVER_OWNER" />
      </n-form-item>
      <n-form-item
        label="可操作人"
        path="operationUser"
        :rule="[{ required: true, message: '可操作人不能为空!' }]"
      >
        <AsyncSelect
          v-if="isRender"
          v-model:value="model.operationUser"
          :options="getUserOptions"
          label-key="name"
          value-key="userId"
          :remote="true"
          :init-remote="true"
          :multiple="true"
        />
      </n-form-item>
      <n-form-item label="规格" path="specification">
        <n-input v-model:value="model.specification" clearable :maxlength="100" />
      </n-form-item>
      <n-form-item label="付费类型" path="payType">
        <AsyncSelect v-model:value="model.payType" options="PAY_TYPE" />
      </n-form-item>
      <n-form-item
        label="时间范围"
        path="timeRange"
        :rule="[{ required: true, message: '时间范围不能为空!' }]"
      >
        <n-date-picker
          v-model:formatted-value="model.timeRange"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm"
          :time-picker-props="{ format: 'HH:mm' }"
          :default-time="['09:00:00', '18:30:00']"
          clearable
          start-placeholder="启用时间"
          end-placeholder="到期时间"
        />
      </n-form-item>
      <n-form-item label="剩余时间">
        <n-input :value="remainder" disabled />
      </n-form-item>
      <n-form-item label="费用(元)" path="money">
        <n-input-number
          v-model:value="model.money"
          :precision="2"
          :min="0"
          :max="100000000"
          clearable
        />
      </n-form-item>
      <n-form-item label="单位" path="unit">
        <AsyncSelect v-model:value="model.unit" options="UNIT" />
      </n-form-item>
    </MyDrawer>
  </div>
</template>
<script setup lang="jsx">
import dayjs from 'dayjs'
import { userSel } from '@/api/user'
import { useCrudPro } from '@/hooks/useCrudPro'
import * as projectApi from '@/api/project'
import { formatToIds, formatToSel } from '@/utils/format'
defineOptions({ name: 'OperateManage' })
const props = defineProps({
  detail: {
    type: Object,
    default: () => ({}),
  },
})
const remainder = computed(() => {
  if (model.value?.timeRange?.length === 2) {
    return `${-dayjs().diff(model.value.timeRange[1], 'day')}天`
  } else {
    return '0天'
  }
})
function getUserOptions(name, userIds) {
  return userSel({ name, userIds: formatToIds(userIds) }).then((res) => res.data)
}
const columns = [
  { title: '区域', key: 'areaStr', width: 120 },
  { title: '服务器IP', key: 'ip', width: 120 },
  { title: '服务器归属', key: 'serverOwnerStr', width: 100 },
  { title: '可操作人', key: 'userName', width: 200 },
  { title: '规格', key: 'specification', width: 200 },
  { title: '付费类型', key: 'payTypeStr', width: 100 },
  {
    title: '启用时间',
    key: 'timeStart',
    width: 200,
    render: ({ timeStart }) => $format(timeStart),
  },
  { title: '到期时间', key: 'timeEnd', width: 200, render: ({ timeEnd }) => $format(timeEnd) },
  {
    title: '剩余时间',
    key: 'remainder',
    width: 200,
    render: ({ timeEnd }) => {
      const diff = -dayjs().diff(timeEnd, 'day')
      if (timeEnd) {
        return diff >= 0 ? `${diff}天` : `${diff}天[已到期]`
      } else {
        return `0天`
      }
    },
  },
  { title: '费用(元)', key: 'money', width: 200 },
  { title: '单位', key: 'unitStr', width: 200 },
  {
    title: '操作',
    key: 'actions',
    width: 220,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          <n-button v-permission="/OMManagement:update" text onClick={() => handleEdit(row)}>
            修改
          </n-button>
          <n-button
            v-permission="/OMManagement:delete"
            text
            onClick={() =>
              handleDelete(row, {
                title: '删除运维',
                content: `请确定是否删除运维：${row.ip}`,
              })
            }
          >
            删除
          </n-button>
        </n-flex>
      )
    },
  },
]
const { type, isRender, model, $form, $table, handleAdd, handleEdit, handleSubmit, handleDelete } =
  useCrudPro({
    name: '服务器',
    initForm: {
      id: null,
      ip: null,
      area: null,
      serverOwner: null,
      operationUser: null,
      specification: null,
      payType: null,
      timeRange: null,
      money: null,
      unit: null,
    },
    apis: {
      add: (params) => projectApi.operateAdd({ ...params, projectId: props.detail.id }),
      edit: projectApi.operateEdit,
      del: ({ id }) => projectApi.operateDel(id),
      info: (info) => {
        info.operationUser = formatToSel(info.operationUser)
        info.timeRange = info.timeStart && info.timeEnd ? [info.timeStart, info.timeEnd] : null
        return info
      },
    },
    formatParams({ timeRange, ...params }) {
      params.operationUser = formatToIds(params.operationUser)
      if (timeRange?.length === 2) {
        const [timeStart, timeEnd] = timeRange
        params.timeStart = timeStart
        params.timeEnd = timeEnd
      }
      return params
    },
  })
watch(
  () => props.detail.id,
  (val) => {
    if (val) {
      nextTick(() => {
        $table.value.handleQuery()
      })
    }
  },
  {
    immediate: true,
  }
)
</script>
<style lang="scss" scoped></style>
